//
//  ForgetPasswordController.swift
//  找回密码界面
//
//  Created by smile on 2019/4/9.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class ForgetPasswordController: BaseLoginController {
    
    /// 倒计时框架
    var countDown:CountDown?
    
    /// 用户名
    @IBOutlet weak var tfUsername: UITextField!
    
    /// 发送验证码按钮
    /// 将Button类型改为custom
    /// 否则更改文本的时候会闪烁
    @IBOutlet weak var btSendCode: UIButton!
    
    /// 验证码
    @IBOutlet weak var tfCode: UITextField!
    
    /// 密码
    @IBOutlet weak var tfPassword: UITextField!
    
    /// 确认密码
    @IBOutlet weak var tfConfirmPassword: UITextField!
    
    /// 重置密码按钮
    @IBOutlet weak var btResetPassword: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    override func initViews() {
        super.initViews()
        //设置标题
        setTitle("找回密码")
        
        //按钮圆角
        ViewUtil.showLargeRadius(view: btResetPassword)
        
        
        //去除返回按钮标题
//        self.navigationController!.navigationBar.topItem!.title = ""
    }
    
    override func initDatas() {
        //初始化倒计时框架
        countDown=CountDown()
        
        
    }
    
    /// 开始倒计时
    /// 现在没有报错退出的状态
    /// 也就说，返回在进来就可以点击了
    func startCountDown() {
        //开始时间
        let startDate=Date()
        
        //结束时间
        //当前时间+60秒
        let endDate=Date(timeIntervalSinceNow: 60)
        countDown?.countDown(withStratDate: startDate, finish: endDate, complete: { (day, hour, minute, second) in
            
            //每秒钟回调一次
            let totoalSecond = day*24*60*60+hour*60*60 + minute*60+second
            
            if (totoalSecond==0) {
                //倒计时完毕
                self.btSendCode.setTitle("发送验证码", for: UIControl.State.normal)
                self.btSendCode.isEnabled=true
                
                
            }else{
                self.btSendCode.setTitle("\(totoalSecond)后重新获取", for: UIControl.State.normal)
                self.btSendCode.isEnabled=false
            }
        })
    }
    
    /// 发送验证码点击事件
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onSendCodeClick(_ sender: UIButton) {
//        startCountDown()
        
        //获取用户名
        let username=tfUsername.text?.trim()
        
        if username!.isEmpty {
            ToastUtil.short("请输入用户名！")
            return
        }
        
        if username!.isPhone() {
            //手机号
            sendSMSCode(username!)
        }else if username!.isEmail(){
            //邮箱
            sendEmailCode(username!)
        }else{
            ToastUtil.short("用户名格式不正确！")
        }
    }
    
    /// 发送短信验证码
    ///
    /// - Parameter username: <#username description#>
    func sendSMSCode(_ username:String) {
        Api.shared
            .sendSMSCode(phone: username)
            .subscribeOnSuccess { (_) in
                //发送成功
                //开始倒计时
                self.startCountDown()
            }.disposed(by: disposeBag)

    }
    
    /// 发送邮件验证码
    ///
    /// - Parameter username: <#username description#>
    func sendEmailCode(_ username:String) {
        Api.shared
            .sendEmailCode(email: username)
            .subscribeOnSuccess { (_) in
                //发送成功
                //开始倒计时
                self.startCountDown()
            }.disposed(by: disposeBag)
        
    }
    
    /// 重置密码点击事件
    ///
    /// - Parameter sender: <#sender description#>
    @IBAction func onResetPasswordClick(_ sender: UIButton) {
        //获取用户名
        let username=tfUsername.text?.trim()
        
        if username!.isEmpty {
            ToastUtil.short("请输入用户名！")
            return
        }
        
        guard username!.isPhone() || username!.isEmail() else {
            //如果用户名，既不是手机号
            //也不是邮箱，就是格式错误
            ToastUtil.short("用户名格式不正确！")
            return
        }
        
        //获取验证码
        let code=tfCode.text?.trim()
        
        if code!.isEmpty {
            ToastUtil.short("请输入验证码！")
            return
        }
        
        guard code!.isCode() else {
            ToastUtil.short("验证码格式不正确！")
            return
        }
        
        //获取密码
        let password=tfPassword.text?.trim()
        
        if password!.isEmpty {
            ToastUtil.short("请输入密码！")
            return
        }
        
        guard password!.isPassword() else {
            ToastUtil.short("密码格式不正确！")
            return
        }
        
        //确认密码
        let confirmPassword=tfConfirmPassword.text!.trim()
        
        if confirmPassword!.isEmpty{
            ToastUtil.short("请输入确认密码！")
            return
        }
        
        guard confirmPassword!.isPassword() else {
            ToastUtil.short("确认密码格式不正确！")
            return
        }
        
        //确认密码判断
        guard password==confirmPassword else {
            ToastUtil.short("两次密码不正确！")
            return
        }
        
        //调用重置密码接口
        //验证码应该在服务端判断
        //客户端判断有风险

        //判断当前用户名是手机号
        //还是邮箱
        var phone:String?
        var email:String?
        
        //判断是手机号还是邮箱
        if username!.isPhone(){
            //手机号
            phone=username
        }else{
            //邮箱
            email=username
        }

        //企业级项目中，这些参数可能会加密
        //我们的服务端接口也是支持的
        //为了讲解课程难度
        //我们就不所有的接口加密
        //就只在订单那边接口实现加密
        Api.shared
            .resetPassword(phone:phone,email:email,code:code!,password:password!)
            .subscribeOnSuccess { (data) in
                //重置成功
                
                //调用登陆接口
                //自动登陆
                
                //调用父类的登录方法
                self.login(phone: phone, email: email, password: password!)
            }.disposed(by: disposeBag)
        
    }
    
    //和OC中的dealloc方法差不多
    deinit {
        countDown!.destoryTimer()
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}
